package com.waterai.util;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.waterai.util.service.ExcelImportService;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class UploadDataListener<T> implements ReadListener<T> {
    private int BATCH_COUNT;
    private List<T> cacheData;
    private ExcelImportService<T> dao;

    public UploadDataListener(ExcelImportService<T> dao) {
        init(dao, 500);
    }

    public UploadDataListener(ExcelImportService<T> dao, int size) {
        init(dao, size);
    }

    public void init(ExcelImportService<T> dao, int size) {
        this.dao = dao;
        this.BATCH_COUNT = size;
        this.cacheData = ListUtils.newArrayListWithExpectedSize(size);
    }


    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        // log.info("解析到一条数据:{}", t);
        cacheData.add(t);
        if (cacheData.size() >= BATCH_COUNT) {
            this.dao.batchSave(cacheData);
            cacheData = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        this.dao.batchSave(cacheData);
        log.info("本次数据存储完毕！");
    }
}
